package org.softmed.rest.server.test.creators.testcases.parameters;

import org.restlet.data.Response;
import org.restlet.data.Status;
import org.softmed.rest.server.test.creators.AbstractTestCaseCreator;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SetFieldNameText extends AbstractTestCaseCreator {

	String fieldName;
	String name = "new name";
	String rootNodeName;
	boolean sucessExpected = true;
	boolean searchInAttributes = true;

	public SetFieldNameText(String rootNodeName, String fieldName, String name) {
		this.name = name;
		this.fieldName = fieldName;
		this.rootNodeName = rootNodeName;
	}

	public SetFieldNameText(String rootNodeName, String fieldName, String name,
			boolean sucessExpected, boolean searchInAttributes) {
		this.name = name;
		this.fieldName = fieldName;
		this.rootNodeName = rootNodeName;
		this.sucessExpected = sucessExpected;
		this.searchInAttributes = searchInAttributes;
	}

	@Override
	public String testCase(String uri, String elementURI) throws Throwable {
		Response response = creator
				.postTEXT(elementURI + "/" + fieldName, name);

		if (!sucessExpected) {
			if (!response.getStatus().equals(Status.CLIENT_ERROR_CONFLICT))
				return elementURI;
			else
				creator.getTestCase().setSucess(true);

			return elementURI;
		}

		if (!response.getStatus().equals(Status.SUCCESS_CREATED))
			return elementURI;

		setupXMLDoc();

		if (!doc.getDocumentElement().getNodeName().equals(rootNodeName))
			return elementURI;

		NamedNodeMap att = doc.getDocumentElement().getAttributes();

		if (att == null)
			return elementURI;

		Node node = att.getNamedItem("uri");
		if (node == null)
			return elementURI;

		String value = node.getNodeValue();
		if (value == null)
			return elementURI;

		if (searchInAttributes) {

			node = att.getNamedItem(fieldName);
			if (node == null)
				return elementURI;

			value = node.getNodeValue();
			if (value == null)
				return elementURI;

			if (!value.equals(name))
				return elementURI;

			creator.getTestCase().setSucess(true);

		} else {

			NodeList childs = doc.getDocumentElement().getElementsByTagName(
					fieldName);
			if (childs.getLength() != 1)
				return elementURI;

			node = childs.item(0);
			if (node == null)
				return elementURI;

			value = node.getTextContent();
			if (value == null)
				return elementURI;

			if (!value.equals(name))
				return elementURI;

			creator.getTestCase().setSucess(true);
		}

		return elementURI;
	}

}
